package com.lagou.xmls;


import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.pojo.MethodType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;


/**
 * @Description:
 * @author liujunling
 * @date 2020/3/31
 */
public class XMLMappersBuilder {
    private Configuration configuration;

    public XMLMappersBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream in) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(in);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> selectElement = rootElement.selectNodes("//select");
        parseStatementElement(selectElement, namespace);
        List<Element> insertElement = rootElement.selectNodes("//insert");
        parseStatementElement(insertElement, namespace);
        List<Element> updateElement = rootElement.selectNodes("//update");
        parseStatementElement(updateElement, namespace);
        List<Element> deleteElement = rootElement.selectNodes("//delete");
        parseStatementElement(deleteElement, namespace);
    }

    private void parseStatementElement(List<Element> element, String namespace) {
        for (Element e : element) {
            String id = e.attributeValue("id");
            String resultType = e.attributeValue("resultType");
            String paramsType = e.attributeValue("paramsType");
            String sql = e.getTextTrim();
            String name = e.getName();
            MethodType methodType = MethodType.valueOf(name.toUpperCase());
            String statementId = namespace + "." + id;
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamsType(paramsType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            mappedStatement.setMethodType(methodType);
            configuration.getMappedStatements().put(statementId, mappedStatement);
        }
    }

}
